﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Ext.Net;

namespace Taxes.Caculate
{
    public partial class Assess : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["curr_user"] == null)
            {
                Response.Redirect("Default.aspx");
            }
            if (!IsPostBack)
            {
                var bll = new BLL.industry_info();
                var topIndustry = bll.GetTopIndustry();
                this.storeIndustryTop.DataSource = topIndustry;
                storeIndustryTop.DataBind();
              

            }
        }
        [DirectMethod]
        public void DeleteFile(string fileName, string fileClientName)
        {
            try
            {
                System.IO.File.Delete(fileName);
                //X.Msg.Notify("提示", fileClientName + "已删除!").Show();
            }
            catch (Exception ex)
            {
                //X.Msg.Notify("提示", fileClientName + "删除失败!").Show();
            }
        }

        [DirectMethod]
        public void industryReload(object sender, DirectEventArgs args)
        {
            cbIndustry.Items.Clear();
            FileUploadField1.Hidden = false;
            ReloadStreoIndustry(null, null);
        }

        public void BtnFloorCancelClick(object sender, DirectEventArgs args)
        {
            window1.Hidden = true;
            tfOriginal.Text = "";
            tfFloorNum.Value = "";
            radioOwer.Checked = false;
            radioZuyong.Checked = false;
            tfArea.Text = "";
            ckLift.Checked = false;
            storeFloor_pic.RemoveAll();

        }

        public void FloorPicSubmit(int floorID, string url)
        {
            var model = new Model.floor_pic();
            model.floor_id = floorID;
            model.pic_url = url;
            var bll = new BLL.floor_pic();
            bll.Add(model);
        }

        [DirectMethod]
        public void FloorSubmit(int revenueID, int floorNumber, int floorUse, decimal floorOriginal, decimal floorArea, int hasLift, decimal totalArea, string picUrls)
        {
            var model = new Model.floor_info();
            model.floor_num = floorNumber;
            model.floor_area = floorArea;
            model.floor_carea = totalArea;
            model.floor_elevator = hasLift;
            model.floor_original = floorOriginal;
            model.floor_use = floorUse;
            model.revenue_id = revenueID;
            var bll = new BLL.floor_info();
            int id = bll.Add(model);
            var strings = picUrls.Split(',');
            foreach (var s in strings)
            {
                if (s.Trim() == string.Empty)
                    continue;
                var temp = s.Substring(s.LastIndexOf("/")+1);
                FloorPicSubmit(id, temp);
            }
        }
        [DirectMethod]
        public int RevenueSubmit(string zhanDiMainji)
        {
            var bll = new BLL.revenue_info();
            var model = new Model.revenue_info();
            model.in_date = DateTime.Now;
            if (cbIndustry.SelectedItem.Value == null)
            {
                model.industry_id = Convert.ToInt32(cbIndustryTop.SelectedItem.Value);
            }
            else
            {
                model.industry_id = Convert.ToInt32(cbIndustry.SelectedItem.Value);
            }
            model.PC_Code = tfComputorCode.Text.Trim();
            model.region_id = Convert.ToInt32(hiddenRegionID.Text);
            model.reve_address = tfAddress.Text.Trim();
            model.reve_area_pic = hidePic.Text.Trim();
            model.reve_name = tfTaxesName.Text.Trim();
            model.reve_operator = ((Model.ysys_user)Session["curr_user"]).ID;
            model.reve_pic = hidValue.Text.Trim();
            model.reve_trent = Convert.ToDecimal(tfCost.Text.Trim());
            model.reve_lon = Convert.ToDecimal(hiddenLon.Text);
            model.reve_lat = Convert.ToDecimal(hiddenLat.Text);

            model.reve_area = Convert.ToDecimal(zhanDiMainji);
            model.Register_Date = DateTime.Now;
            model.Register_status = "正常";
            return bll.Add(model);

        }
        [DirectMethod]
        public void ShowImage(object sender, DirectEventArgs args)
        {
            if (this.fileUploadPic.HasFile)
            {
                string strImg = string.Empty;
                if (fileUploadPic.PostedFile != null && fileUploadPic.PostedFile.ContentLength > 0)
                {
                    strImg = this.fileUploadPic.PostedFile.FileName;
                    string strExt = System.IO.Path.GetExtension(strImg).ToLower();
                    if (strExt != ".jpg" && strExt != ".jepg" && strExt != ".bmp" && strExt != ".gif" && strExt != ".png")
                    {
                        X.Msg.Show(new MessageBoxConfig
                        {
                            Buttons = MessageBox.Button.OK,
                            Icon = MessageBox.Icon.WARNING,
                            Title = "提示",
                            Message = "抱歉仅支持.jpg，jepg，bmp，gif"
                        });
                        return;
                    }
                    SaveFile(strImg);
                }
            }
        }

        [DirectMethod]
        public void GetImage(object sender, DirectEventArgs arg)
        {
            if (this.FileUploadField1.HasFile)
            {
                string strImg = string.Empty;
                if (FileUploadField1.PostedFile != null && FileUploadField1.PostedFile.ContentLength > 0)
                {
                    strImg = this.FileUploadField1.PostedFile.FileName;
                    string strExt = System.IO.Path.GetExtension(strImg).ToLower();
                    if (strExt != ".jpg" && strExt != ".jepg" && strExt != ".bmp" && strExt != ".gif" && strExt != ".png")
                    {
                        X.Msg.Show(new MessageBoxConfig
                        {
                            Buttons = MessageBox.Button.OK,
                            Icon = MessageBox.Icon.WARNING,
                            Title = "提示",
                            Message = "抱歉仅支持.jpg，jepg，bmp，gif"
                        });
                        return;
                    }
                    EXIF.GPSData gps;

                    if (fileUpload(strImg, out gps))
                    {
                        ///说明有gps信息
                        var bll = new BLL.revenue_info();
                        int region_houseold, industry_household, regionID;
                        string regionName = string.Empty;
                        decimal region_unit_price, region_unit_rent, industry_unit_rent, tax_loaded_region, tax_loaded_industry;
                        region_unit_price = region_unit_rent = industry_unit_rent = tax_loaded_region = tax_loaded_industry = region_houseold = industry_household = regionID = 0;
                        decimal lon = gps.Longitude.Degrees + (decimal)gps.Longitude.Minutes / 60 + gps.Longitude.Seconds / 3600;
                        decimal lat = gps.Latitude.Degrees + (decimal)gps.Latitude.Minutes / 60 + gps.Latitude.Seconds / 3600;
                        hiddenLon.Text = lon.ToString();
                        hiddenLat.Text = lat.ToString();
                        int industryID;
                        if (cbIndustryTop.SelectedItem.Value == null)
                        {
                            X.Msg.Show(new MessageBoxConfig
                            {
                                Buttons = MessageBox.Button.OK,
                                Icon = MessageBox.Icon.WARNING,
                                Title = "提示",
                                Message = "请先选择行业!"
                            });
                            return;
                        }
                        if (cbIndustry.SelectedItem.Value != null)
                        {
                            industryID = Convert.ToInt32(cbIndustry.SelectedItem.Value);
                        }
                        else
                        {
                            industryID = Convert.ToInt32(cbIndustryTop.SelectedItem.Value);
                        }
                        bll.GetRevenueInfo(lon, lat, industryID, ref regionName, ref region_unit_price, ref region_unit_rent, ref region_houseold, ref industry_unit_rent, ref industry_household, ref tax_loaded_region, ref tax_loaded_industry, ref regionID);
                        lblRegion.Text = regionName;
                        lblUnitRegionCost.Text = region_unit_rent + "元/" + region_houseold + "户";
                        lblInudstryUnitRegionTaxes.Text = tax_loaded_industry.ToString();
                        lblUnitRegionTaxesPrecent.Text = tax_loaded_region.ToString();
                        lblSystemUnitCost.Text = region_unit_price.ToString() + "元";


                        lblIndustryUnitCost.Text = industry_unit_rent + "元" + industry_household + "户";
                        hiddenRegionID.Text = regionID.ToString();

                        lblUnitRegionCost.Show();
                        lblInudstryUnitRegionTaxes.Show();
                        lblUnitRegionTaxesPrecent.Show();
                        lblSystemUnitCost.Show();
                        lblRegion.Show();

                        lblIndustryUnitCost.Show();
                        tfCost.Show();
                        //显示提交按钮
                        btnSubmit.Show();
                    }
                    else
                    {
                        ///说明不是gps照片
                        X.Msg.Show(new MessageBoxConfig
                        {
                            Buttons = MessageBox.Button.OK,
                            Icon = MessageBox.Icon.WARNING,
                            Title = "提示",
                            Message = "请上传包含gps信息照片的图片"
                        });
                        return;
                    }

                    lblLon.Text = gps.Longitude.Degrees + "°" + gps.Longitude.Minutes + "'" + gps.Longitude.Seconds + "\"";
                    lblLat.Text = gps.Latitude.Degrees + "°" + gps.Latitude.Minutes + "'" + gps.Latitude.Seconds + "\"";
                    lblLat.Show();
                    lblLon.Show();
                }
            }
        }

        protected void FloorBtnClick(object send, DirectEventArgs e)
        {
            var bll = new BLL.floor_convert();
            var model = new Model.floor_info();
            model.floor_num = int.Parse(tfFloorNum.Text);
            int max;
            int min;
            bll.MaxMinFloor(ckLift.Checked, out max, out min);
            if (model.floor_num < min && model.floor_num > max)
            {
                X.Msg.Show(new MessageBoxConfig()
                {
                    Title = "提示",
                    Message = "楼层号请输入" + min + "到" + max + "之间的数值!",
                    Buttons = MessageBox.Button.OK
                });
                return;
            }
            model.floor_area = decimal.Parse(tfArea.Text);
            if (ckLift.Checked)
            {
                model.floor_original = decimal.Parse(tfOriginal.Text);
            }
            else
            {
                model.floor_original = 0;
            }
            model.floor_use = radioZuyong.Checked ? 1 : radioOwer.Checked ? 0 : 0;
            model.floor_elevator = ckLift.Checked ? 1 : 0;
            model.uriFloorImage = imageUrlHidden.Text;
            decimal original = 0;
            if (decimal.TryParse(tfOriginal.Text, out original))
            {
                model.floor_original = original;
            }

            ///取折算率.折算面积

            var m = bll.GetModelByFloorNumAndLift(model.floor_num, ckLift.Checked);
            model.floor_carea = model.floor_area * m.floor_converter;


            storeFloor.AddRecord(model);

            hidTotalMianJi.Text = string.IsNullOrEmpty(hidTotalMianJi.Text) ? model.floor_carea.ToString() : (Convert.ToDecimal(hidTotalMianJi.Text) + model.floor_carea).ToString();
            lblTotalMianJi.Text = hidTotalMianJi.Text;
            window1.Hidden = true;
            tfOriginal.Text = "";
            tfFloorNum.Value = "";
            radioOwer.Checked = false;
            radioZuyong.Checked = false;
            tfArea.Text = "";
            ckLift.Checked = false;
            storeFloor_pic.RemoveAll();
        }



        protected void ReloadStreoIndustry(object sender, StoreRefreshDataEventArgs e)
        {
            int id = 0;
            if (int.TryParse(this.cbIndustryTop.SelectedItem.Value, out id))
            {
                var bll = new BLL.industry_info();
                var induftry = bll.GetIndustryByParentID(id);
                this.streoIndustry.DataSource = induftry;
                streoIndustry.DataBind();
            }

        }

        public void SaveFile(string strFilePath)
        {
            string strPictureName = string.Empty;//上传后的图片名，以当前时间为文件名，确保文件名没有重复  
            if (!string.IsNullOrEmpty(strFilePath))
            {
                try
                {
                    string strFileName = System.IO.Path.GetFileName(strFilePath);
                    strPictureName = DateTime.Now.Ticks.ToString() + strFileName;
                    string strMapPath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["UploadPath"].ToString());
                    string strPath = strMapPath + "\\" + strPictureName;
                    fileUploadPic.PostedFile.SaveAs(strPath);
                    //hidePic.Text = System.Configuration.ConfigurationManager.AppSettings["UploadPath"].ToString() + "/" + strPictureName;
                    hidePic.Text = strPictureName;
                    picImage.ImageUrl = System.Configuration.ConfigurationManager.AppSettings["UploadPath"].ToString() + "/" + strPictureName;
                    picImage.Show();
                }
                catch (Exception ex)
                {
                    Response.Write(ex);
                }
            }
        }
        public bool fileUpload(string strFilePath, out EXIF.GPSData data)
        {
            string strPictureName = string.Empty;//上传后的图片名，以当前时间为文件名，确保文件名没有重复  
            data = null;
            if (!string.IsNullOrEmpty(strFilePath))
            {
                try
                {
                    string strFileName = System.IO.Path.GetFileName(strFilePath);
                    strPictureName = DateTime.Now.Ticks.ToString() + strFileName;
                    string strMapPath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["UploadPath"].ToString());
                    string strPath = strMapPath + "\\" + strPictureName;
                    FileUploadField1.PostedFile.SaveAs(strPath);
                    ///判断是不是包含经纬度
                    var exif = new EXIF.Exif(new System.Drawing.Bitmap(strPath));
                    data = exif.GPSData;
                    if (data != null)
                    {
                        //hidValue.Text = System.Configuration.ConfigurationManager.AppSettings["UploadPath"].ToString() + "/" + strPictureName;
                        hidValue.Text = strPictureName;
                        imageShow.ImageUrl = System.Configuration.ConfigurationManager.AppSettings["UploadPath"].ToString() + "/" + strPictureName;
                        imageShow.Show();
                        return true;
                    }
                    else { return false; }

                }
                catch (Exception ex)
                {
                    Response.Write(ex);
                }

            }
            else
            {
                X.Msg.Show(new MessageBoxConfig
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.NONE,
                    Title = "提示",
                    Message = "请选择照片"
                });
            }
            return true;
        }
    }
}